package com.snail.permission.runtime.setting;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import com.snail.permission.source.Source;

/**
 * @author zhaoyan
 * @date 2019-03-18
 */
public class SettingPage {

    private final static String SCHEME = "package";
    //调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.1及之前版本)
    private final static String APP_PKG_NAME_21 = "com.android.settings.ApplicationPkgName";
    //调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.2)
    private final static String APP_PKG_NAME_22 = "pkg";
    //InstalledAppDetails所在包名
    private final static String APP_DETAILS_PACKAGE_NAME = "com.android.settings";
    //InstalledAppDetails类名
    private final static String APP_DETAILS_CLASS_NAME = "com.android.settings.InstalledAppDetails";

    private static final String MARK = Build.MANUFACTURER.toLowerCase();

    private Source mSource;

    public SettingPage(Source source) {
        this.mSource = source;
    }

    /**
     * 看以后产品需求，这个入口是先跳转到系统应用权限管理设置页，需要用户选择应用，点击进入权限管理页
     * 根据不同厂商做不同的跳转，默认是系统设置api
     * Start.
     */
    public void start() {
        start(-1);
    }

    /**
     * 看以后产品需求，这个入口是先跳转到系统应用权限管理设置页，需要用户选择应用，点击进入权限管理页
     * 根据不同厂商做不同的跳转，默认是系统设置api
     * Start.
     *
     * @param requestCode this code will be returned in onActivityResult() when the activity exits.
     */
    public void start(int requestCode) {
        //产品决策跳转系统的应用信息页
        start(requestCode, false);
    }

    /**
     * 目前有的手机管家的权限管理页的权限显示不全，用户找不到开关入口，产品决策跳转系统的应用信息页
     *
     * @param requestCode
     * @param defaultApi  是否调用系统api
     */
    private void start(int requestCode, boolean defaultApi) {
        Intent intent;
        if (defaultApi) {
            intent = defaultApi(mSource.getContext());
        } else {
            //优先跳转到手机管家的权限设置页，若跳转手机管家权限设置页失败，则跳转系统的应用信息
            if (MARK.contains("huawei")) {
                intent = huaweiApi(mSource.getContext());
            } else if (MARK.contains("xiaomi")) {
                intent = xiaomiApi(mSource.getContext());
            } else if (MARK.contains("oppo")) {
                intent = oppoApi(mSource.getContext());
            } else if (MARK.contains("vivo")) {
                intent = vivoApi(mSource.getContext());
            } else if (MARK.contains("meizu")) {
                intent = meizuApi(mSource.getContext());
            } else {
                intent = defaultApi(mSource.getContext());
            }
        }
        try {
            if (requestCode < 0) {
                mSource.startActivity(intent);
            } else {
                mSource.startActivityForResult(intent, requestCode);
            }
        } catch (Exception e) {
            //跳转异常
            Log.d(SettingPage.class.getSimpleName(), "e = " + e.toString());
        }
    }

    private Intent defaultApi(Context context) {
        Intent intent = new Intent();
        final int apiLevel = Build.VERSION.SDK_INT;
        if (apiLevel >= 9) {
            // 2.3（ApiLevel 9）以上，使用SDK提供的接口
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts(SCHEME, context.getPackageName(), null);
            intent.setData(uri);
        } else {
            // 2.3以下，使用非公开的接口（查看InstalledAppDetails源码）
            // 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。
            final String appPkgName = (apiLevel == 8 ? APP_PKG_NAME_22
                    : APP_PKG_NAME_21);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName(APP_DETAILS_PACKAGE_NAME,
                    APP_DETAILS_CLASS_NAME);
            intent.putExtra(appPkgName, context.getPackageName());
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        return intent;
    }

    private Intent huaweiApi(Context context) {
        Intent intent = new Intent();
        intent.setClassName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
        if (hasActivity(context, intent)) return intent;

        return defaultApi(context);
    }

    private Intent xiaomiApi(Context context) {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.putExtra("extra_pkgname", context.getPackageName());
        if (hasActivity(context, intent)) return intent;

        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
        if (hasActivity(context, intent)) return intent;

        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
        if (hasActivity(context, intent)) return intent;

        return defaultApi(context);
    }

    private Intent vivoApi(Context context) {
        Intent intent = new Intent();
        intent.putExtra("packagename", context.getPackageName());
        intent.setClassName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity");
        if (hasActivity(context, intent)) return intent;

        intent.setClassName("com.iqoo.secure", "com.iqoo.secure.safeguard.SoftPermissionDetailActivity");
        if (hasActivity(context, intent)) return intent;

        return defaultApi(context);
    }

    private Intent oppoApi(Context context) {
        Intent intent = new Intent();
        intent.putExtra("packageName", context.getPackageName());
        intent.setClassName("com.color.safecenter", "com.color.safecenter.permission.PermissionManagerActivity");
        if (hasActivity(context, intent)) return intent;

        intent.setClassName("com.oppo.safe", "com.oppo.safe.permission.PermissionAppListActivity");
        if (hasActivity(context, intent)) return intent;

        return defaultApi(context);
    }

    private Intent meizuApi(Context context) {
        Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
        intent.putExtra("packageName", context.getPackageName());
        intent.setClassName("com.meizu.safe", "com.meizu.safe.security.AppSecActivity");
        if (hasActivity(context, intent)) return intent;

        return defaultApi(context);
    }

    private boolean hasActivity(Context context, Intent intent) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
    }
}